﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool {
    //对象池里要存的对象
	public GameObject Prefab { get; private set; }
    //池子的名字 
    public string Name { get; private set; }
    //对象池的最大容量
    public int MaxCount { get; private set; }

    //池子里所有对象
    public List<GameObject> PrefabList;
    //构造函数用来初始化
    public ObjectPool(GameObject prefab,string name,int maxCount)
    {
        PrefabList = new List<GameObject>();
        this.Prefab = prefab;
        this.Name = name;
        this.MaxCount = maxCount;
    }
    //得到一个对象
    public GameObject GetObject()
    {
        GameObject go = null;
        for (int i = 0; i < PrefabList.Count; i++)
        {
            if (!PrefabList[i].activeSelf)//如果被隐藏
            {
                PrefabList[i].SetActive(true);//就设置active为true
                go = PrefabList[i];
                break;
            }
        }
        if (go == null)
        {
            if (PrefabList.Count >= MaxCount)//如果集合大于最大数量
            {
                GameObject.Destroy(PrefabList[0]);//销毁第一个对象
                PrefabList.RemoveAt(0);//并且移除对象池
            }
            go = GameObject.Instantiate<GameObject>(Prefab);//新创建一个对象
            PrefabList.Add(go);//并加入列表            
        }
        go.SendMessage("BeforeGetObject", SendMessageOptions.DontRequireReceiver);
        return go;
    }
    //隐藏某一个对象
    public void HideObject(GameObject go)
    {
        if (PrefabList.Contains(go))
        {
            go.SendMessage("BeforeHideObject", SendMessageOptions.DontRequireReceiver);
            go.SetActive(false);
        }
    }
    //隐藏对象池所有的对象
    public void HideAllObject()
    {
        for (int i = 0; i < PrefabList.Count; i++)
        {
            if (PrefabList[i].activeSelf)
            {
                HideObject(PrefabList[i]);
            }             
        }
    }
}
